package ub.pis.net;

import java.io.UnsupportedEncodingException;

import java.net.URL;
import java.net.URLEncoder;

import javax.xml.parsers.SAXParser;
import java.net.MalformedURLException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.util.Log;

/**
 * Parser que se encarga de pedir una corrección al servidor de last.fm
 * y retornar el nombre corregido si es necesario.
 * @author nagash
 *
 */
public class ArtistCorrectionParser {
	final String apiGetCorrection = "http://ws.audioscrobbler.com/2.0/?method=artist.getcorrection&artist=";
	final String apiKey = "&api_key=f63681e32bd85bcbd6ccf3fddd60d618";

	private URL xmlUrl;
	
	/**
	 * Constructor del parser.
	 * @param artist
	 * @throws UnsupportedEncodingException
	 */
	public ArtistCorrectionParser(String artist)
			throws UnsupportedEncodingException {
		artist = URLEncoder.encode(artist, "UTF-8");
		String xml = apiGetCorrection + artist + apiKey;
		Log.i("URL", xml);
		try {
			this.xmlUrl = new URL(xml);
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Retorna la correción del artista usando ArtistCorrectionXMLHandler
	 * @return String
	 */
	public String parse() {
		SAXParserFactory spf = SAXParserFactory.newInstance();

		try {

			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			ArtistCorrectionXMLHandler handler = new ArtistCorrectionXMLHandler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(xmlUrl.openStream()));

			return handler.getCorrection();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
